<?php
namespace Utuo;

use My\Model\MallOrderModel;
use My\Model\WechatUserModel;
use Home\Logic\MallRedPacketLogic;

class MallOrderController extends MallForeground {
	
	// 购物车
	protected $cart = null;
	
	
	/**
	 * 初始化
	 */
	public function _init() {
		layout ( 'Mall/layout' );
		$this->setModelName ( "Mall" );
		$this->setModelControllerName( "Mall" );
		$this->cart = $this->getCart ();
	}
	
	/**
	 * 我的订单
	 */
	public function listAction() {
		$type = I ( "type" );
		$m = M ( "MallOrder orders" );
		$condition = array (
			"orders.uid" => $this->uid,
		);
		
		if ($type == 1) { // 未付款
			$condition ['orders.order_status'] = MallOrderModel::ORDER_STATUS_PAY;
		} else if ($type == 2) { // 待签收(已付款,货到付款)
			$condition ['orders.order_status'] = array (
					"in",
					array (
							MallOrderModel::ORDER_STATUS_SHIPPING,
							MallOrderModel::ORDER_STATUS_SIGN
					)
			);
			unset( $condition['orders.uid'] );
			/* 送礼订单 */
			$m->join ( "__MALL_GIFTS__ gifts on orders.id = gifts.order_id", "LEFT" );
			$condition['orders.id'] = array('exp', "is not null and (
																((gifts.to_uid=0 or gifts.to_uid is null) and orders.uid={$this->uid}) 
																	or 
																(gifts.to_uid={$this->uid})
															) ");
		} else if ($type == 3) { // 交易成功
			$condition ['orders.order_status'] = MallOrderModel::ORDER_STATUS_COMPLETED;
		}  else if ($type == 4) { // 退款订单
			$condition['orders.refund_times'] = array('gt', 0);
		} else { // 其它
			$condition ['orders.order_status'] = array (
					"not in",
					array (
							MallOrderModel::ORDER_STATUS_PAY,
							MallOrderModel::ORDER_STATUS_SHIPPING,
							MallOrderModel::ORDER_STATUS_SIGN,
							MallOrderModel::ORDER_STATUS_COMPLETED,
					),
			);
		}
		$orderLists = $m->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
						->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
						->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
						->field ( "orders.*,province.name as provinceName, city.name as cityName, area.name as areaName" )
						->where ( $condition )->order("orders.id desc")->select ();
		$this->bindOrderDetail ( $orderLists );
		$this->assign("types", \My\Model\MallOrderModel::$TYPES);
		$this->assign ( "orderLists", $orderLists );
		$this->display ( "{$this->modelControllerName}/orderList" );
	}
	
	/**
	 * 订单结算页
	 */
	public function confirmOrderAction() {
		$orderId = I('orderId', 0, "intval");
		$order = array();
		if ( $orderId ) {
			$order = $this->getPayingOrder( $orderId );
		} else {
			$order = $this->getSaveingOrder();
			session ( "order", $order );
		}
		$redPacketsLists = MallRedPacketLogic::getRedPacketsUseable($this->uid, $order['goodsTotalPrice']);
		$this->assign ( "redPacketsLists", $redPacketsLists );
		$this->assign ( "orderJSON", json_encode ( $order ) );
		$this->assign ( 'order', $order );
		$this->assign ( "buyUrl", urlencode($this->getCurrentUrl ()) );
		$this->display ( "{$this->modelControllerName}/" . ACTION_NAME );
	}
	
	/**
	 * 获得已保存欲支付订单
	 * @return array 格式参考getSaveingOrder
	 */
	protected function getPayingOrder( $id ) {
		$addressId = I('addressId', 0, "intval");
		$order = $this->getOrder($id);
		if ( $order ) {
			/* 支付方式下拉框(在确认订单页显示支付方式,直接转入支付接口) */
			$produtPayApiLists = $this->getPayApiList();
			if ( $order['support_cod']*1 ) {
				$produtPayApiLists = array_merge($produtPayApiLists, array('COD' =>"货到付款"));
			}
			/* 转化为确认订单可显示的格式 */
			$order['createTime'] = $order['create_time'];
			$order['orderNo'] = $order['order_id'];
			$order['totalPrice'] = sprintf("%.2f", $order['goods_amount'] + $order['shipping_fee']);
			$order['goodsTotalPrice'] = $order['goods_amount'];
			$order['shippingTotalPrice'] = $order['shipping_fee'];
			$order['productPayApiOptions'] =  $this->getOption( $produtPayApiLists );	
			/* 收货地址 */
			if ( $addressId ) {
				$address = $this->getAddress($addressId);
			} else {
				$address = array(
					'name' => $order['consignee'],
					'province' => $order['province'],
					'city' => $order['city'],
					'area' => $order['area'],
					'address' => $order['address'],
					'tel' => $order['tel'],
					'provinceName' => $order['provinceName'],
					'cityName' => $order['cityName'],
					'areaName' => $order['areaName'],
				);
			}
			$order['address'] = $address;	
			/* 订单之前选择的红包 */
			if ( $order['red_packet_id'] ) {
				$order['redPacketId'] = $order['red_packet_id'];
				$order['redPacketCode'] = M("MallRedPacket")->where(array('id'=>$order['red_packet_id']))->getField('code');
				$order['redPacketOffset'] = $order['red_packet_offset'];
			}
			foreach ( explode(',', "create_time,order_id,goods_amount,shipping_fee,consignee,province,city,area,tel") as $v ) {
				unset($order[$v]);
			}
			foreach ( $order['orderItems'] as $productId => &$productItems ) {
				$productItems['name'] = $productItems['productName'];
				foreach ( $productItems['items'] as $businessId => &$items) {
					$items['quantity'] = $items['productNumber'];
					$items['attrs'] = $items['productAttr'];
					$items['pic'] = $items['productPic'];
					unset($items['productNumber']);
					unset($items['productAttr']);
					unset($items['productPic']);
					unset($items['rate_status']);
				}
				unset($productItems['productName']);
			}
			return $order;
		}
	}
	
	/**
	 * 获得欲保存订单
	 * @return
	 * array(
	 *  ["atOnce"] => int(1)
	 *  ["createTime"] => int(1417767435)
	 *  ["orderNo"] => string(22) "1412051617150000011771"
	 *  ["totalPrice"] => float(138)
	 *  ["goodsTotalPrice"] => float(138)
	 *  ["shippingTotalPrice"] => float(0)
	 *  ["productPayApiOptions"] => string(46) "<option value='WxTenpay'>微信支付</option>"
	 *  ["orderItems"] => array(1) {
	 *  ["8"] => &array(4) {
	 *    ["productId"] => string(1) "8"
	 *    ["name"] => string(26) "阿芙薰衣草精油10ml "
	 *    ["support_cod"] => string(1) "0"
	 *    ["items"] => array(1) {
	 *      ["b123198bb0678beddc453e07c57bbc48c8141776743580"] => &array(5) {
	 *        ["businessId"] => string(46) "b123198bb0678beddc453e07c57bbc48c8141776743580"
	 *        ["productPrice"] => string(6) "138.00"
	 *        ["quantity"] => int(1)
	 *        ["attrs"] => NULL
	 *        ["pic"] => string(72) "http://wmei-wmei5.stor.sinaapp.com/2014-11-14/2014111411424640164318.jpg"
	 *      }
	 *    }
	 *  }
	 * }
	 * ["supportCod"] => int(0)
	 * ["address"] => array(13) {
	 *   ["id"] => string(1) "1"
	 *   ["uid"] => string(2) "29"
	 *   ["name"] => string(6) "宋义"
	 *   ["province"] => string(6) "230000"
	 *   ["city"] => string(6) "230200"
	 *   ["area"] => string(6) "230204"
	 *   ["zipcode"] => string(0) ""
	 *   ["address"] => string(15) "ewqrewqrewqrewq"
	 *   ["tel"] => string(11) "13849089206"
	 *   ["status"] => string(1) "1"
	 *   ["provinceName"] => string(12) "黑龙江省"
	 *   ["cityName"] => string(15) "齐齐哈尔市"
	 *   ["areaName"] => string(9) "铁锋区"
	 * }
	 * )
	 */
	protected function getSaveingOrder() {
		$d = D ( "My/MallGoods", "Model" );
		$items = $this->getItems(); // 获得要结算的商品
		$totalPrice = 0; // 总价
		$supportCod = 1; // 默认支持货到付款
		foreach ( $items ["items"] as &$v ) {
			$count = 0; // 购买数量
			$subtotal = 0; // 小计
			/* 判断订单中每件商品是否支持货到付款，从而求出整个订单是否支持货到付款  */
			if ( !$v['support_cod']*1 ) $supportCod = 0;
			/* 处理显示属性可看 */
			foreach ( $v ['items'] as &$v0 ) {
				$count += $v0 ['quantity'];
				$subtotal += $v0 ['productPrice'] * $v0 ['quantity'];
			}
			$totalPrice += $subtotal;
			/* 计算运费 */
			$shippingPrice = $d->getShipping ( $v['productId'], $count );
			$totalShpping += $shippingPrice;
		}
		
		// 支付方式下拉框(在确认订单页显示支付方式,直接转入支付接口)
		$produtPayApiLists = $this->getPayApiList();
		if ( $supportCod ) {
			$produtPayApiLists = array_merge($produtPayApiLists, array('COD' =>"货到付款"));
		}
		$order = array (
				'atOnce' => $items ["atOnce"],
				'createTime' => time (),
				'orderNo' => date ( "ymdHis" ) . str_pad ( $this->sid, 6, 0, STR_PAD_LEFT ) . rand ( 1000, 9999 ), // 订单号
				'totalPrice' => $totalPrice + $totalShpping,
				'goodsTotalPrice' => $totalPrice,
				'shippingTotalPrice' => $totalShpping, // 配送方式数据(确认订单,更改地址时使用)
				'productPayApiOptions' => $this->getOption( $produtPayApiLists ),
				'orderItems' => $items ["items"],
				'supportCod' => $supportCod,
		);
		
		/* 获得用户默认收货地址 */
		$order ['address'] = $this->getAddress();
		
		/* 附加数据 */
		method_exists($this, '_after_get_saving_order') and $this->_after_get_saving_order( $order );
		return $order;
	}
	
	/**
	 * 确认支付订单
	 */
	public function confirmOrderPostAction() {
		$orderId = I('orderId', 0, "intval"); // 订单id
		$orderNo = I ( 'orderNo', 0 ); // 订单单号
		$payApitype = I("apitype", ""); // 支付方式
		$buyMethod = I("buyMethod", 0, "intval"); // 购买方式
		
		if ( !$orderId ) {
			$orderId = $this->addOrder($orderNo, $payApitype);
		} else {
			$order = M("MallOrder")->where('id=%d', $orderId)->find();
			/** 更新订单 */
			$data = array();
			$addressId = I('addressId', 0, "intval");
			/* 更新订单收货地址 */
			$address = $this->getAddress($addressId, 0);
			if ( $address ) {
				$data = array_merge($data, array(
					'consignee' => $address ['name'],
					'province' => $address ['province'],
					'city' => $address ['city'],
					'area' => $address ['area'],
					'address' => $address ['address'],
					'zipcode' => $address ['zipcode'],
				));
			}
			/* 更新选择使用的红包 */
			$packetCode = I('packetCode', '');
			$redPacket = M("MallRedPacket")->where(array('uid'=>$this->uid, 'code'=>$packetCode, 'efficacy'=>1))->find();
			if ( $redPacket ) {
				if ( $redPacket != $order['red_packet_id'] ) {
					$data['red_packet_id'] = $redPacket['id'];
					$data['red_packet_offset'] = $redPacket['value'];
					$data['actual_cost'] = array('exp', "goods_amount+shipping_fee-{$redPacket['value']}");
					$data['order_id'] = MallOrderModel::randOrderNo($this->sid); // 订单号
				}
			} else {
				if ( $order['red_packet_id'] ) {
					$data['red_packet_id'] = 0;
					$data['red_packet_offset'] = 0;
					$data['actual_cost'] = array('exp', "goods_amount+shipping_fee");
					$data['order_id'] = MallOrderModel::randOrderNo($this->sid); // 订单号
				}
			}
			$data and M("MallOrder")->where(array('uid'=>$this->uid, 'id'=>$orderId))->save($data);
		}

		/* 购买方式下的订单处理 */
		if ( $buyMethod == MallOrderModel::BUY_METHOD_COQUETRY ) { // 找人代付订单
			redirect(U("MallCoquetryOrder/payAnother", "id={$orderId}&sid={$this->sid}")); // 转入发起页
		} else {
			/* 支付转入 */
			if ( empty($payApitype) ) {
				$order = $this->getOrder ( $orderId );
				$this->assign ( "order", $order );
				$this->display ( "{$this->modelControllerName}/showOrder" );
			} else {
				redirect($this->getPayUrl(array(
					'id' => $orderId,
					'sid' => $this->cid,
					'apitype' => $payApitype,
				)));
			}
		}
		exit ();
	}
	
	/**
	 * 添加订单
	 */
	public function addOrder( $orderNo, $payApitype ) {
		$order = session ( "order" ); // 要保存的订单
		$addressLists = $order ['addressLists'];
		
		/* 购买时的代理商  */
		$aid = cookie("aid"); // 代理商id
		if ( $this->uid == $aid ) {
			$aid = 0;
		}
		
		/* 获得订单 */
		if ( !$order || $order ['orderNo'] !== $orderNo ) {
			$orderSaved = M("MallOrder")->where(array( 'order_id'=>$orderNo, 'cid'=>$this->cid) )->find();
			if ( $orderSaved ) { // 订单已存在时
				$this->error ( "订单($orderNo)已超时,正在转向订单详细重新结算.",  U('MallOrder/showOrder', "id={$orderSaved['id']}&sid={$this->cid}"));
			} elseif ( !$order || $order and (time () - $order ["createTime"]) > 3 * 60 ) { // 下单超时
				$this->error ( "订单($orderNo){$order ['orderNo']}已超时,正在转向购物车重新结算.",  $this->getCartUrl());
			}
		}
		
		/* 是否支持货到付款 */
		if( $payApitype == "COD" ) {
			if ( !$order['supportCod'] ) {
				$this->error ( "当前订单不支持货到付款" );
			}
		}
		
		/* 获得收货地址 */
		$deliverAddress = $this->getAddress();
		$deliverAddress or $this->error ( "没有找到默认的收货地址" );
		
		/* 配送费 */
		$shippingTotalPrice = $order ['shippingTotalPrice']; // 配送信息
		
		/* 保存订单 */
		$orderData = array (
				'order_id' => $orderNo,
				'cid' => $this->cart->getCid(),
				'uid' => $this->cart->getUid (),
				'agent_id' => $aid*1, // 支持代理模式
				'shipping_fee' => $shippingTotalPrice,
				'goods_amount' => $order ['goodsTotalPrice'],
				'order_status' => MallOrderModel::ORDER_STATUS_PAY,
				'consignee' => $deliverAddress ['name'],
				'province' => $deliverAddress ['province'],
				'city' => $deliverAddress ['city'],
				'area' => $deliverAddress ['area'],
				'address' => $deliverAddress ['address'],
				'zipcode' => $deliverAddress ['zipcode'],
				'tel' => $deliverAddress ['tel'],
				'express_name' => '',
				'create_time' => $order ['createTime'],
				'confirm_time' => 0,
				'shipping_time' => 0,
				'support_cod' => $order['supportCod'],
		);
		
		$offset = 0; // 抵消金额
		
		/* 使用的优惠卷 */
		$packetCode = I('packetCode', '');
		$packetCode and ( $redPacket = M("MallRedPacket")->where(array('uid'=>$this->uid, 'code'=>$packetCode, 'efficacy'=>1))->find() or $this->error ( "您选择了无效的优惠卷" ) );
		if ( $redPacket ) {
			$orderData['red_packet_offset'] = $offset = $redPacket['value'];
			$orderData['red_packet_id'] = $redPacket['id'];
		}
		
		/* 实际消费总额 */
		$orderData['actual_cost'] = $order ['goodsTotalPrice'] + $shippingTotalPrice - $offset;
		
		/* 订单添加前 */
		method_exists($this, "_before_add_order") and $this->_before_add_order( $orderData );
		
		$d = D ( "MallOrder" );
		if ( $orderId = $d->add ( $orderData ) ) {
			$orderData['id'] = $orderId;
			// 添加所有订单商品
			$m = M ( "MallOrderGoods" );
			$goodsList = $this->getOrderGoods( $order['orderItems'], $orderId);
			if ( false != $m->addAll ( $goodsList ) ) {
				$order ['atOnce'] or $this->cart->clearAll ();
				session ( "order", null );
				/*订单创建后操作*/
				method_exists($this, "_after_add_order") and $this->_after_add_order( $orderData );
				/*更新订单总佣金*/
				$baseRewards = MallOrderModel::calcRewardBonus($goodsList);
				$dealerRewards = MallOrderModel::calcRewardBonusDealer($goodsList);
				$baseBonus = array_sum(array_values($baseRewards['totalUser']));
				$dealerBonus = array_sum(array_values($dealerRewards['totalUser']));
				$d->where('id=%d', $orderId)->save(array(
						'total_bonus' => $baseRewards['orderBonus'] + $dealerRewards['orderBonus'],
						'reward_uids' => join(',', array_keys($baseRewards['totalUser'])),
						'reward_bonus' => join(',', array_values($baseRewards['totalUser'])),
						'reward_uids_dealer' => join(',', array_keys($dealerRewards['totalUser'])),
						'reward_bonus_dealer' => join(',', array_values($dealerRewards['totalUser'])),
						'surplus' => $order ['goodsTotalPrice'] - ( $baseBonus + $dealerBonus ), // 盈余 = 订单总额 - ( 基础分成总额 + 特约经销商分成总额  )
				));
				return $orderId;
			} else {
				$d->where ( "id=%d", $orderId )->setField ( "order_status", MallOrderModel::ORDER_STATUS_INVALID );
			}
		}
		$this->error ( '订单保存错误.' );
	}
	
	/**
	 * 确认收货
	 */
	public function signInAction() {
		$orderId = I ( "id", 0, "int" );
		$d = M ( "MallOrder" );
		$order = $d->find( $orderId );
		if($order['order_status'] == MallOrderModel::ORDER_STATUS_SIGN) {
			// 更新订单状态
			$data = array("order_status" => MallOrderModel::ORDER_STATUS_COMPLETED,
						"take_time" => time(),
						"deal_time" => time(),);
			if( false !== $d->where ( array ( "uid" => $this->uid, "id" => $orderId, ) )
							->save ( $data ) ) {
								$order = array_merge($order, $data);
								$this->afterOrderCompleted( $order );
								$this->ajaxSuccess ( "交易成功" );
			}
		} else {
			$this->ajaxError ( "非已发货状态，不能完成收货操作。" );
		}
		$this->ajaxError ( "提交失败，请重新确认收货" );
	}
	
	
	/**
	 * 获得要结算的商品
	 * 立即购买:
	 * $_GET = array(
	 * 	  'id' => 0,
	 * 	  'quantity' => 1,
	 * 	  'attrs' => array(
	 * 		  '属性1' => '属性值1'
	 * 	   ),
	 * )
	 * @return array
	 * array(
	 * 	  "atOnce" => 0, // 是否立即购买
	 * 	  "items" => array (
	 * 			array(
	 * 				$businessId => array(
	 * 					'businessId' => $businessId,
	 * 					'productPrice' => 0.00,
	 * 					'quantity' => $quantity,
	 * 					'attrs' => array(
	 * 						'属性名1' => '属性值1',
	 * 					),
	 * 					'pic' => '',
	 * 				)
	 * 			),
	 * 			... ...
	 * 	  ),
	 * )
	 */
	protected function getItems() {
		$items = array (
				"atOnce" => 0, // 是否立即购买
				"items" => array ()
		);
		$goodsId = I ( "id", 0, "intval" ); // 商品id(立即购买时)
		if ( !$goodsId ) { // 处理从购物车中选择的商品
			$items ["items"] = $this->cart->getItems (); // 暂时购买所有商品
		} elseif( $goodsId ) { // 处理立即购买的商品
			$id = I ( "id", 0, "intval" );
			$quantity = I ( "quantity", 1, "intval" ) and $quantity === 0 and $quantity = 1;
			$attrs = I ( "attrs", null );
			$d = D ( "My/MallGoods", "Model" );
			// 处理立即购买属性参数,如果提交类型为数组则转为字符串类型(购买链接会再次使用)
			$goods = $d->getUserSubmitGoods ( $id, $attrs );
			if ( !$goods ) {
				if ( IS_AJAX )
					$this->ajaxError ( $d->getError () );
				else
					$this->error ( $d->getError () );
			}
			// 转化为CartItem(参考购物车结构)
			$businessId = $this->cart->getBusinessId ( $goods ['id'] );
			$items ["atOnce"] = 1;
			$items ["items"] [$goods ['id']] = array (
					'productId' => $goods ['id'],
					'name' => $goods ['name'],
					'support_cod' => $goods ['support_cod'],
					'items' => array (
							$businessId => array (
								'businessId' => $businessId,
								'productPrice' => $goods ['productPrice'],
								'quantity' => $quantity,
								'attrs' => $goods ['selectedAttributes'],
								'pic' => $goods['images'][0] ? $goods['images'][0] : '',
							)
					)
			);
		}
		return $items;
	}
	
	/**
	 * 获得可持久化的订单商品数据
	 * @param unknown $orderItems
	 * @param unknown $orderId
	 * @return multitype:multitype:unknown NULL
	 */
	protected function getOrderGoods( $orderItems, $orderId ) {
		$goodsList = array();
		foreach ( $orderItems as $v ) {
			/* 分成商品 */
			$shopGoods = M("MallGoods")->where(array('cid'=>$this->cid, 'id'=>$v['productId']))->find();
			
			/* 创建可保存的订单商品格式 */
			foreach ( $v ["items"] as $v0 ) {
				/* 分成信息 */
				$res = $this->getPercentAndUsers($shopGoods, $v0);
				$base = $res['base'];
				$uids = $base[0];
				$rewardPercent = $base[1];
				$rewardPrice = $base[2];
					
				$dealer = $res['dealer'];
				$franchisedDealerUids = $dealer[0];
				$rewardPercentDealer = $dealer[1];
				$rewardPriceDealer = $dealer[2];
				
				$rewardBonus = MallOrderModel::calcSimpleRewardBonus($uids, $rewardPercent, $v0['quantity']*$rewardPrice);
				$rewardBonusDealer = MallOrderModel::calcSimpleRewardBonus($franchisedDealerUids, $rewardPercentDealer, $v0['quantity']*$rewardPriceDealer);
				$orderGoodsItem = array (
						'order_id' => $orderId,
						'product_id' => $v ['productId'],
						'product_name' => $v ['name'],
						'product_pic' => $v0 ['pic'],
						'product_number' => $v0 ['quantity'],
						'product_price' => $v0 ['productPrice'],
						'product_attr' => arrayToString ( $v0 ['attrs'] ),
						/* 基础 */
						'reward_price' => $rewardPrice, // 佣金/件
						'reward_uids' => join(',', $uids), // 返佣金用户
						'reward_percent' => join(':', $rewardPercent), // 佣金比例
						'reward_bonus' => join(',', $rewardBonus),
						/* 特约经销商 */
						'reward_price_dealer' => $rewardPriceDealer, // 特约经销商佣金/件
						'reward_uids_dealer' => join(',', $franchisedDealerUids), // 返佣金特约经销商用户
						'reward_percent_dealer' => join(':', $rewardPercentDealer), // 佣金比例
						'reward_bonus_dealer' => join(',', $rewardBonusDealer),
				);
				$goodsList [] = $orderGoodsItem;
			}
				
		}
		return $goodsList;
	}
	
	/**
	 * 获得订单中一个产品的分成比例与分成用户
	 * @param array $shopGoods 所买商品
	 * @param array $orderGoodsItem 订单商品（支付前的订单商品格式,即getItems的格式）
	 * @return multitype:multitype:multitype: unknown
	 */
	protected function getPercentAndUsers( $shopGoods, $orderGoodsItem ) {
		
		/* 基础佣金 */
		$rewardPrice = $shopGoods['reward_price']; // 基础佣金
		
		/* 特约经销商佣金 */
		$rewardPriceDealer = $shopGoods['reward_price_dealer']; // 特约经销商佣金
		
		/* 特约经销购买时 */
		if ( $this->user['type'] == WechatUserModel::USER_TYPE_FRANCHISED_DEALER ) { // 特约经销商
			if ( $shopGoods['dealer_price'] - $orderGoodsItem['productPrice'] == 0 ) { // 以会员价购买更改佣金
				$rewardPrice = $shopGoods['reward_price2'];
				$rewardPriceDealer = $shopGoods['reward_price2_dealer'];
			}
		}
		
		/* 基础分成发放比例 */
		$rewardPercent = array();
		if ( $shopGoods['reward_set'] ) { // 商品设置的分成比例
			$shopGoods['reward_percent'] and $rewardPercent = explode(':', $shopGoods['reward_percent']);
		} else { // 系统默认分成比例
			$this->config['reward_percent'] and $rewardPercent = explode(':', $this->config['reward_percent']);
		}
		
		/* 获得参与佣金发放的用户  */
		$tree = M("MallUserTree")->where(array('cid'=>$this->cid, 'uid'=>$this->uid))->getField("tree");
		$uids = explode(',', $tree);
		array_shift($uids);
		
		/* 特约经销商分成发放比例  */
		$rewardPercentDealer = array();
		if ( $shopGoods['reward_set_dealer'] ) { // 商品设置的分成比例
			$shopGoods['reward_percent_dealer'] and $rewardPercentDealer = explode(':', $shopGoods['reward_percent_dealer']);
		} else { // 系统默认分成比例
			$this->config['reward_percent_dealer'] and $rewardPercentDealer = explode(':', $this->config['reward_percent_dealer']);
		}
		
		/* 用户筛选出特约经销商 */
		$franchisedDealerUids = array();
		$userInfo = array();
		if ( $uids ) {
			$exceptDealer = 0; // 分成除去代理用户  0.不除 1.去除(代理商用户分成将并入基础用户分成)
			$userInfo = M("WechatUser")->where(array('id'=>array('in', $uids)))->order("find_in_set(id, '{$tree}')")->getField("id,type");
			for ( $i=0; $i < count($uids); $i++ ) {
				if ( $userInfo[$uids[$i]] == WechatUserModel::USER_TYPE_AGENT ) { // 代理用户
					if ( $exceptDealer ) {
						$uids = array_slice($uids, 0, $i); // 筛选出非代理用户
						continue;
					}
				} elseif ( $userInfo[$uids[$i]] == WechatUserModel::USER_TYPE_FRANCHISED_DEALER ) { // 筛选特约经销商用户 (从非代理用户)
					$franchisedDealerUids[] = $uids[$i];
				} else {
					$franchisedDealerUids[] = 0; // 非特约经销商补0
				}
			}
		}
		
		/* 基础分成用户与分成比例 */
		$uids = array_slice($uids, 0, count($rewardPercent)); // 分配比例 -> 裁剪分销用户
		$rewardPercent = array_slice($rewardPercent, 0, count($uids));  // 分销用户 -> 裁剪分配比例
		
		/* 用户与分成比例 (特约经销商)*/
		$franchisedDealerUids = array_slice($franchisedDealerUids, 0, count($rewardPercentDealer)); // 分配比例 -> 裁剪分销用户
		$rewardPercentDealer = array_slice($rewardPercentDealer, 0, count($franchisedDealerUids));  // 分销用户 -> 裁剪分配比例
		$uidCount = count($franchisedDealerUids);
		for( $i = 0; $i < $uidCount; $i++ ) { // 清除uid为0的用户
			if ( !$franchisedDealerUids[$i]*1 ) {
				unset($franchisedDealerUids[$i]);
				unset($rewardPercentDealer[$i]);
			}
		}
		return array(
			'base' => array($uids, $rewardPercent, $rewardPrice),
			'dealer' => array($franchisedDealerUids, $rewardPercentDealer, $rewardPriceDealer),
		);
	}
	
	
	/**
	 * 交易成功后
	 * @param int $orderId
	 */
	protected function afterOrderCompleted( $order ) {
	    $orderId = $order['id'];
	    $surplus = $order['surplus'];
		if ( $surplus > 0 ) {
		    M("MallOrderSettleAccounts")->add(array(
		        'cid' => $order['cid'],
		        'order_id' => $order['id'],
		        'from_agent' => 0, // 从系统发出
		        'to_agent' => 0, // 无代理商(由总厂家处理)
		        'surplus' => $surplus, // 盈余
		    ));
		}

		/* 更新用户产品推广 */
		$this->updateUserProductPromotion( $orderId );
		
		/* 更新用户销费总金额 */
		/*$m = M("WechatUser");
		$wechatUser = $m->where("id=%d", $order['uid'])->find();
		$saveData = array(
			'sellsCost' => array('exp', "sellsCost+{$order['goods_amount']}"),
		);
		/* 自动成为金牌会员 */
		/*if ( $wechatUser['type'] == WechatUserModel::USER_TYPE_STANDARD and 
			( $wechatUser['sellsCost'] + $order['goods_amount'] ) >= $this->config['dealer_min_sells'] ) {
			 $saveData['type'] = WechatUserModel::USER_TYPE_FRANCHISED_DEALER;
		}
		$m->where("id=%d", $order['uid'])->save($saveData);*/
		
		/** 用户拥金结算 */
		/* 基础佣金 */
		$uids = explode(',', $order['reward_uids']);
		$bonus = explode(',', $order['reward_bonus']);
		$bonusUser = array_combine($uids, $bonus);
		
		/* 特销商佣金 */
		$uids = explode(',', $order['reward_uids_dealer']);
		$bonus = explode(',', $order['reward_bonus_dealer']);
		$bonusDealerUser = array_combine($uids, $bonus);
		
		/* 佣金合并 */
		foreach ( $bonusUser as $k => $v) {
			$bonusUser[$k] += $bonusDealerUser[$k];
		}
		
		/* 更新用户佣金收入与推广订单数量  */
		if ( $bonusUser ) {
			$setBonusFields = array();
			foreach ( $bonusUser as $k => $v) {
				$setBonusFields[] = "WHEN {$k} THEN bonus+{$v}";
			}
			$setBonusFields = join(' ', $setBonusFields);
			M("WechatUser")->where(array('id' => array('in', array_keys($bonusUser))))
						->save(array('bonus' => array('exp', "CASE id {$setBonusFields} END"),
									'orderCount' => array('exp', 'orderCount+1')));
		}
	}
	
	/**
	 * 更新用户产品推广
	 */
	protected function updateUserProductPromotion( $order ) {
		$uid = $order['uid'];
		$orderId = $order['orderId'];
		$cid = $order['cid'];
		$goodsList = M("MallOrderGoods")->where("order_id=%d", $orderId)->select();
		$productUserGoods = array(
			/*'用户id' => array(
				'产品id' => array(
					'saledTotal(销售总和)' => 0.00,
					'rewardsTotal(佣金)' => 0.00,
					'dealerRewardsTotal(特约佣金)' => 0.00,
				),
			),*/
		);
		foreach ( $goodsList as $v) {
			/*分配佣金*/
			if ( $v['reward_uids'] ) {
				$userBonus = array_combine(explode(',', $v['reward_uids']), explode(',', $v['reward_bonus']));
				/*特销商佣金*/
				if ( $v['reward_uids_dealer'] ) {
					$userBonusDealer = array_combine(explode(',', $v['reward_uids_dealer']), explode(',', $v['reward_bonus_dealer']));
				}
				/*各用户下*/
				foreach ( $userBonus as $uid => $bonus ) {
					/*各商品佣金*/
					$productUserGoods[$uid][$v['product_id']]['orderCount'] = 1;
					$productUserGoods[$uid][$v['product_id']]['saledTotal'] += $v['product_number']*$v['product_price']; // 消售总额
					$productUserGoods[$uid][$v['product_id']]['rewardsTotal'] += $userBonus[$uid]*1; // 基础佣金总额
					$productUserGoods[$uid][$v['product_id']]['dealerRewardsTotal'] += $userBonusDealer[$uid]*1; // 特销商佣金总额
				}
			}
		}
		foreach ( $productUserGoods as $uid => $pros ) {
			foreach ( $pros as $productId => $pro ) {
				$m = M("MallGoodsPromotion");
				$dsgp = $m->where('uid=%d and productId=%d', $uid, $productId)->find();
				if ( $dsgp ) {
					$m->where('uid=%d and productId=%d', $uid, $productId)->data(array(
						'orderCount' => array('exp', "orderCount+{$pro['orderCount']}"),
						'saledTotal' => array('exp', "saledTotal+{$pro['saledTotal']}"),
						'rewardsTotal' => array('exp', "rewardsTotal+{$pro['rewardsTotal']}"),
						'dealerRewardsTotal' => array('exp', "dealerRewardsTotal+{$pro['dealerRewardsTotal']}"),
					))->save();
				} else {
					$m->add(array(
						'cid' => $cid,
						'uid' => $uid,
						'productId' => $productId,
						'orderCount' => $pro['orderCount'],
						'saledTotal' => $pro['saledTotal'],
						'rewardsTotal' => $pro['rewardsTotal'],
						'dealerRewardsTotal' => $pro['dealerRewardsTotal'],
					));
				}
			}
		}
	}
	
	/**
	 * 订单详细
	 */
	public function showOrderAction() {
		$id = I ( "id", 0, "intval" );
		$order = $this->getOrder ( $id );
		/* 待支付订单跳转入重新进入确认页 */
		if ( in_array('pay', $order['operates'] ) ) { // 支付
			$controller = "MallOrder";
			if ( $order['buy_method'] == MallOrderModel::BUY_METHOD_GIFTS ) {
				$controller = 'MallGiftsOrder';
			} elseif ( $order['buy_method'] == MallOrderModel::BUY_METHOD_TRY ) {
				$controller = 'MallTryOrder';
			}
			redirect(U("{$controller}/confirmOrder", array('sid'=>$this->cid, 'orderId'=>$id)));
		} elseif ( in_array('payAnother', $order['operates'] ) ) { // 发起代付
			/* 代支付订单跳转  */
			if ( $order['buy_method'] == MallOrderModel::BUY_METHOD_COQUETRY ) {
				$controller = "MallCoquetryOrder";
				redirect(U("{$controller}/confirmOrder", array('sid'=>$this->cid, 'orderId'=>$id)));
			}
		}
		$this->assign ( "order", $order );
		$this->display ( "{$this->modelControllerName}/showOrder" );
	}
	
	/**
	 * 取消订单
	 */
	public function cancelOrderAction() {
		$orderId = I ( "id", 0, "int" );
		$d = M ( "MallOrder" );
		$d->where ( array (
				"uid" => $this->uid,
				"id" => $orderId
		) )->setField ( "order_status", MallOrderModel::ORDER_STATUS_CANCELED ) and $this->ajaxSuccess ( "取消成功" );
		$this->ajaxError ( "取消失败" );
	}
	
	/**
	 * 获得用户收货地址
	 * @param $auto 自动寻找默认
	 * @return array
	 */
	protected function getAddress( $addressId = 0, $auto = 1 ) {
		$condition = array(
			'address.uid' => $this->uid,
			'address.status' => 1,
		);
		if ( $addressId ) {
			$condition['address.id'] = $addressId;
			unset($condition['address.status']);
		} elseif ( !$auto ) {
			return null;
		}
		$address = M ( "MallDeliverAddress address" )->join ( "__CN_PROVINCE__ province on address.province = province.code", "LEFT" )
										->join ( "__CN_CITY__ city on address.city = city.code", "LEFT" )
										->join ( "__CN_AREA__ area on address.area = area.code", "LEFT" )
										->field ( "address.*,province.name as provinceName, city.name as cityName, area.name as areaName" )
										->where ( $condition )
										->order ( "address.status desc" )
										->find ();
		return $address;
	}
	
	
	/**
	 * 绑定订单详细
	 * @param unknown $orderLists 查询出的订单列表
	 */
	protected function bindOrderDetail(&$orderLists) {
		D( "My/MallOrder" )->bindOrderDetail($orderLists);
	}
	
	/**
	 * 获得订单操作
	 * @param array $order 已获得详细信息的订单
	 * @return string
	 */
	protected function getOrderOperate( $order ) {
		return D( "My/MallOrder" )->getOrderOperate( $order );
	}
	
	
	/**
	 * 获得一个订单
	 * @param unknown $id
	 * @return array
	 */
	protected function getOrder($id) {
		return D( "My/MallOrder" )->getOrder($id);
	}
	
	/**
	 * 购物车页
	 */
	protected function getCartUrl() {
		return url ( null, 'MallCart', 'showCart', "sid={$this->sid}" );
	}
	
	/**
	 * 获得购物车
	 */
	protected function getCart() {
		return \Utuo\MallCart::getCart ($this->uid, $this->sid );
	}
	
	/**
	 * 支付方式列表
	 * @return multitype:
	 */
	protected function getPayApiList() {
		$m = M("ProductPayApi");
		$produtPayApiLists = $m->where("cid=%d and status=1", $this->sid)->getField("tag,name") or $produtPayApiLists = array(); // 获得商家设置的支付接口
		return $produtPayApiLists;
	}
	
	/**
	 * 获得支付链接
	 * array(
	 * 	'id' => '', // 订单id
	 * 	'sid' => '', // 客户id
	 * 	'apitype' => '', // 支付方式
	 * )
	 */
	protected function getPayUrl($params) {
		$url = __APP__."/".MODULE_NAME."/MallPay/toPay?id={$params['id']}&sid={$params['sid']}&apitype={$params['apitype']}";
		return $url;
	}
	
	/**
	 * 添加订单之前的处理函数
	 * @param unknown $orderData
	 */
	protected function _before_add_order( &$orderData ) {}
	
	
	/**
	 * 添加订单之后的处理函数
	 * @param unknown $orderData
	 */
	protected function _after_add_order( &$orderData ) {}
	
	/**
	 * 获得欲下订单数据后
	 * @param unknown $savingOrderData
	 */
	protected function _after_get_saving_order( &$savingOrderData ) {}
}